package com.liuke.question4.utils;

import java.io.*;
import java.nio.Buffer;
import java.nio.charset.StandardCharsets;

/**
 * @Auther: 刘科
 * @Date: 2021/07/04/9:16
 * @Description:
 */
public class FileUtil {

    public static String getCurrentPath() {
        return new File("").getAbsoluteFile().getPath();
    }

    public static File[] getFiles() {
        return new File("./").listFiles();
    }

    public static void printFiles() {
        File[] files = new File("./").listFiles();
        for (File file : files) {
            System.out.println(file.getName());
        }
    }

    /**
     * 检测文件是否存在
     * @param command
     * @param filename
     * @return
     */
    public static String checkFile(String command, String filename) {
        File file = new File(getCurrentPath() + File.separatorChar + filename);
        //文件不存在
        if (!file.exists()) {
            return String.format("%s: %s: No such file or directory", command, filename);

        }
        //判断是文件还是目录
        if (file.isDirectory()) {
            return String.format("%s %s: Is a directory", command, filename);
        }
        return null;
    }

    public static String readFile(String filename) throws IOException {
        return readFile(new File(filename));
    }
    public static String readFile(File file) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(file);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream, StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        while (bufferedReader.ready()) {
            sb.append((char) bufferedReader.read());
        }
        fileInputStream.close();
        bufferedReader.close();
        return sb.toString();
    }

    public static int getLinesCount(File file) throws IOException {
        FileInputStream fi = new FileInputStream(file);
        BufferedReader bi = new BufferedReader(new InputStreamReader(fi, StandardCharsets.UTF_8));

        int resultCount = 0;
        while (bi.ready()) {
            bi.readLine();
            resultCount++;
        }
        fi.close();
        bi.close();
        return resultCount;
    }

}
